<template>
  <div class="user-page">
    <!-- <el-card shadow="never" class="user-search-bar">
      <div style="display:flex;justify-content:space-between;align-items:center;">
        <el-form :inline="true" :model="searchForm" @submit.prevent>
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card> -->
    <el-card shadow="never" class="user-table-card">
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="70" align="center" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="nickname" label="昵称" min-width="100" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="role" label="角色" min-width="100">
          <template #default="scope">
            <span>
              {{ roleMap[scope.row.role] || scope.row.role }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="状态" min-width="80">
          <template #default="scope">
            <el-tag :type="scope.row.enabled ? 'success' : 'danger'">
              {{ scope.row.enabled ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="expireTime" label="过期时间" min-width="160" />
        <el-table-column prop="createTime" label="创建时间" min-width="160">
          <template #default="scope">
            <span>{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="small" :type="scope.row.enabled ? 'warning' : 'success'" @click="handleToggleStatus(scope.row)">
              {{ scope.row.enabled ? '封禁' : '解封' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    
    </el-card>
    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户" width="400px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="editForm.password" type="password" placeholder="不修改请留空" show-password />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="editForm.nickname" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option label="访客" value="VISITOR" />
            <el-option label="会员" value="MEMBER" />
            <el-option label="管理员" value="ADMIN" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="editForm.enabled" active-text="正常" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { getUserList, updateUser, deleteUser, banUser, unbanUser, getUserDetail } from '../api/user';
import { ElMessage, ElMessageBox } from 'element-plus';

const searchForm = reactive({
  username: '',
  phone: ''
});
const userList = ref([]);

const editDialogVisible = ref(false);
const editForm = ref({});

const roleMap = {
  ADMIN: '管理员',
  MEMBER: '会员',
  VISITOR: '访客'
};


const fetchUsers = async () => {
  try {
    const res = await getUserList();
    userList.value = Array.isArray(res) ? res : [];
 
  } catch (e) {
    console.error('获取用户列表失败', e);
    ElMessage.error('获取用户列表失败');
  }
};

const handleSearch = () => {

  fetchUsers();
};
const handleReset = () => {
  searchForm.username = '';
  searchForm.phone = '';

  fetchUsers();
};
const handlePageChange = (val: number) => {
 
  fetchUsers();
};

const handleEdit = async (row: any) => {
  // 可选：可用getUserDetail(row.id)获取更详细信息
  editForm.value = { ...row };
  editDialogVisible.value = true;
};
const submitEdit = async () => {
  try {
    const data = { ...editForm.value };
    if (!data.password) {
      delete data.password; // 留空则不传递
    }
    await updateUser(data);
    ElMessage.success('保存成功');
    editDialogVisible.value = false;
    fetchUsers();
  } catch (e) {
    ElMessage.error('保存失败');
  }
};
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', { type: 'warning' })
    .then(async () => {
      await deleteUser(row.id);
      ElMessage.success('删除成功');
      fetchUsers();
    })
    .catch(() => {});
};
const handleToggleStatus = async (row: any) => {
  try {
    if (row.enabled) {
      await banUser(row.id);
      ElMessage.success('已封禁');
    } else {
      await unbanUser(row.id);
      ElMessage.success('已解封');
    }
    fetchUsers();
  } catch (e) {
    ElMessage.error('操作失败');
  }
};

function formatDate(val: string) {
  if (!val) return '';
  return val.replace('T', ' ').slice(0, 19);
}

onMounted(() => {
  fetchUsers();
});
</script>

<style scoped>
.user-page {
  padding: 0;
}
.user-search-bar {
  margin-bottom: 18px;
  border-radius: 8px;
}
.user-table-card {
  border-radius: 8px;
}
</style> 